package com.cssw.fyzb.busi.api.pay;

import com.cssw.fyzb.busi.config.TpsClient;
import com.cssw.fyzb.core.exception.BizException;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author: yangyiqun
 * @Date: 2020/7/14 22:10
 */

@Function(description = "ada订单查询", parameters = {
        @Parameter(name = "tradeNo", type = Type.String, description = "流水号", required = true),
        @Parameter(name = "userId", type = Type.String, description = "用户标识", required = true)
})
@Component
public class AdapayQuery implements Action {

    private static final Logger logger = LoggerFactory.getLogger(AdapayQuery.class);
    @Autowired
    private TpsClient tpsClient;

    @Override
    public Response execute(Request request) throws Exception {
        Long userId = request.getLong("userId");
        String tradeNo = request.getString("tradeNo");

        try {
            Map<String, String> map = orderQuery(tradeNo);

            logger.info(tradeNo + ">>>AdapayQuery:" + userId + ">>>" + map);
            if (map == null) {
                return Response.fail("服务异常");
            }
            return Response.success().put("data", map);
        } catch (BizException e){
            return Response.fail(e.getErrMsg(), e.getErrCode());
        } catch (Exception e){
            logger.error("", e);
            return Response.fail("服务异常");
        }
    }


    private Map orderQuery(String tradeNo) {
        Request request = new Request("QueryAdapay");
        request.setParameter("tradeNo", tradeNo);
        Response response = tpsClient.send(request);
        if (!response.isSuccess()) {
            throw new BizException(response.getCode(), response.getMessage());
        }
        return response.getData().get("data", Map.class);

    }
}